﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;
using System.Diagnostics;
using VedioOnline.Tools.Dao;

namespace VideoOnline.FFmpeg
{
    public class Main
    {
        BaseDao dao = new BaseDao();
        public  HttpContext context
        {
            get;
            set;
        }
        public void Test(string FileDir,string OutPutDir,string VideoName)
        {
            //var sourcePath = Environment.CurrentDirectory + "\\Source";

            //string fileName = "File" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + exName;
            //if (Directory.Exists(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd"))) == false)//如果不存在就创建file文件夹
            //{
            //    Directory.CreateDirectory(Server.MapPath("~/upload/" + DateTime.Now.ToString("yyyyMMdd")));
            //}

            var sourcePath = HttpContext.Current.Server.MapPath("~/Upload/Source");
            var sdi = new DirectoryInfo(sourcePath);
            for (var i = 0; i < sdi.GetFiles().Length; i++)
            {
                var f = sdi.GetFiles()[i];
                //var topTwo = f.Name.Substring(0, 2).ToUpper();//目录名称
                var topTwo = DateTime.Now.ToString("yyyyMMddHHmmss");//目录名称

                var videoname = f.Name.Substring(f.Name.LastIndexOf("\\") + 1, f.Name.LastIndexOf(".") - f.Name.LastIndexOf("\\") - 1);


                //var d = new DirectoryInfo(Environment.CurrentDirectory + "\\Target\\video\\" + topTwo);
                //var tflv = new FileInfo(d.FullName + "\\" + videoname + ".flv");


                //if (!d.Exists) d.Create();
                //生成flv
                //if (!tflv.Exists)
                //{
                //    VideoUtil.ConvertFlv(f.FullName, tflv.FullName);
                //}



                //生成m3u8
                var d = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Upload/OutPut/") + topTwo);
                if (!d.Exists) d.Create();
                var tm3u8 = new FileInfo(d.FullName + "\\" + videoname + ".m3u8");
                if (!tm3u8.Exists)
                {
                    ConvertM3U8(f.FullName, d.FullName, videoname);
                }
            }


        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="FileDir">包含文件名的路径</param>
        /// <param name="VideoName">视频文件名</param>
        public void Transformation(string FileDir, string VideoName,string VideoId)
        {
            var topTwo = DateTime.Now.ToString("yyyyMMddHHmmss");//目录名称

            //生成m3u8
            var d = new DirectoryInfo(context.Server.MapPath("~/Upload/OutPut/") + topTwo);
            if (!d.Exists) d.Create();
            var tm3u8 = new FileInfo(d.FullName + "\\" + VideoName + ".m3u8");
            string OutputPath = "/upload/OutPut/" + topTwo;
            string m3u8Path = OutputPath + "/" + VideoName + ".m3u8";


            if (!tm3u8.Exists)
            {
                    
                ConvertM3U8(FileDir, d.FullName, VideoName);
                Dictionary<string, object> map = new Dictionary<string, object>()
                {
                    ["OutputPath"] = OutputPath,
                    ["m3u8Path"] = m3u8Path,
                    ["State"] = 2,
                };
                dao.update("t_d_UpLoadVideo", map, "VideoId=" + VideoId);

            }

        }



        public bool ConvertM3U8(string sourceFlv, string m3u8path, string m3U8Name)
        {
            try
            {
                //文件名称,生成M3U8文件
               // var tool = Environment.CurrentDirectory + @"\ffmpeg\ffmpeg.exe";
                var tool = context.Server.MapPath("~/ffmpeg/ffmpeg/ffmpeg.exe");


                var command = " -i \"" + sourceFlv + "\"  -c:v libx264 -c:a aac -strict -2 -f hls -hls_list_size 0 -hls_time 30 " + m3U8Name + ".m3u8";
                Process _p;
                using (_p = new Process())
                {
                    _p.StartInfo.WorkingDirectory = m3u8path;
                    RedirectRun.RedirectExcuteProcess(_p, tool, command, (s, e) => WriteLog(e.Data, m3u8path));
                }

                return true;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message.ToString());
                return false;
            }
        }

        public static void WriteLog(String data,string path)
        {
            try
            {
                if (!String.IsNullOrEmpty(data))
                {
                    if (!Directory.Exists(path))//如果日志目录不存在就创建
                    {
                        Directory.CreateDirectory(path);
                    }
                    string filename = "Transformation.log";
                    //创建或打开日志文件，向日志文件末尾追加记录
                    StreamWriter mySw = File.AppendText(path + "\\" + filename);

                    //向日志文件写入内容
                    mySw.WriteLine(data);
                    //关闭日志文件
                    mySw.Close();
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                
            }

        }


    }


    public class RedirectRun
    {
        /// <summary>
        /// 功能：重定向执行
        /// </summary>
        /// <param name="p"></param>
        /// <param name="exe"></param>
        /// <param name="arg"></param>
        /// <param name="output"></param>
        public static void RedirectExcuteProcess(Process p, string exe, string arg, DataReceivedEventHandler output)
        {
            p.StartInfo.FileName = exe;
            p.StartInfo.Arguments = arg;

            p.StartInfo.UseShellExecute = false;    //输出信息重定向
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardOutput = true;

            p.OutputDataReceived += output;
            p.ErrorDataReceived += output;

            p.Start();                    //启动线程
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();
            p.WaitForExit();            //等待进程结束
        }
    }
}